package gui;

import dto.ObraSocialDTO;
import fs.Data;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import javax.mail.MessagingException;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.InputMap;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import jr.LiquidacionJR;
import jr.Reporter;
import static jr.Reporter.LiquidacionObraSocialReport;
import kalendar.calendar.JMonthChooser;
import logic.LiquidacionObraSocial;
import logic.ObraSocial;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
import util.CSVExporter;
import util.Email;

/**
 *
 * @author lucifer
 */
public class LiquidacionObraSocialDialog extends javax.swing.JDialog {

  public static final int RET_CANCEL = 0;
  public static final int RET_OK = 1;

  private ArrayList<Integer> osIDs;
  
  public LiquidacionObraSocialDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    setUpObraSocialComboBox(obraSocialjComboBox);

    String cancelName = "cancel";
    InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
    ActionMap actionMap = getRootPane().getActionMap();
    actionMap.put(cancelName, new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        doClose(RET_CANCEL);
      }
    });
  }

  public int getReturnStatus() {
    return returnStatus;
  }

  private void setUpObraSocialComboBox(JComboBox c) {
    ArrayList<ObraSocialDTO> dtos = null;
    try {
      dtos = ObraSocial.All();
    } catch (Exception e) {
      // no hay obras sociales registradas
      dtos = new ArrayList<>();
    }
    osIDs = new ArrayList<>();
    String[] obraSociales = new String[dtos.size() - 1]; // -1 los particulares

    for (int i = 0; i < obraSociales.length; i++) {
      if (dtos.get(i).getId() == 0) {
        continue;
      }
      osIDs.add(dtos.get(i).getId());
      obraSociales[i] = dtos.get(i).getNombre();
    }
    c.setModel(new DefaultComboBoxModel(obraSociales));
    c.setSelectedIndex(-1);
  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    okButton = new javax.swing.JButton();
    cancelButton = new javax.swing.JButton();
    obraSocialjComboBox = new javax.swing.JComboBox();
    mesjMonthChooser = new JMonthChooser(false);
    aniojYearChooser = new kalendar.calendar.JYearChooser();
    jLabel1 = new javax.swing.JLabel();
    emailjCheckBox = new javax.swing.JCheckBox();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Liquidación de Obras Sociales");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        closeDialog(evt);
      }
    });

    okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/aceptar.png"))); // NOI18N
    okButton.setText("Aceptar");
    okButton.setMaximumSize(new java.awt.Dimension(120, 27));
    okButton.setMinimumSize(new java.awt.Dimension(120, 27));
    okButton.setPreferredSize(new java.awt.Dimension(120, 27));
    okButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        okButtonActionPerformed(evt);
      }
    });

    cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/cancelar.png"))); // NOI18N
    cancelButton.setText("Cancelar");
    cancelButton.setMaximumSize(new java.awt.Dimension(120, 27));
    cancelButton.setMinimumSize(new java.awt.Dimension(120, 27));
    cancelButton.setPreferredSize(new java.awt.Dimension(120, 27));
    cancelButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cancelButtonActionPerformed(evt);
      }
    });

    obraSocialjComboBox.setMaximumSize(new java.awt.Dimension(192, 25));
    obraSocialjComboBox.setMinimumSize(new java.awt.Dimension(192, 25));
    obraSocialjComboBox.setPreferredSize(new java.awt.Dimension(192, 25));

    mesjMonthChooser.setMaximumSize(new java.awt.Dimension(115, 25));
    mesjMonthChooser.setMinimumSize(new java.awt.Dimension(115, 25));
    mesjMonthChooser.setPreferredSize(new java.awt.Dimension(115, 25));

    aniojYearChooser.setMaximumSize(new java.awt.Dimension(64, 25));
    aniojYearChooser.setMinimumSize(new java.awt.Dimension(64, 25));
    aniojYearChooser.setPreferredSize(new java.awt.Dimension(64, 25));

    jLabel1.setText("Obra Social:");

    emailjCheckBox.setSelected(true);
    emailjCheckBox.setText("Enviar email con archivo de liquidación a la obra social");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGap(6, 6, 6)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addGroup(layout.createSequentialGroup()
            .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(emailjCheckBox)
            .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel1)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(obraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
              .addComponent(mesjMonthChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(aniojYearChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(aniojYearChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(mesjMonthChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(obraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jLabel1)))
        .addGap(18, 18, 18)
        .addComponent(emailjCheckBox)
        .addGap(18, 18, 18)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap())
    );

    getRootPane().setDefaultButton(okButton);

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
      int sel = obraSocialjComboBox.getSelectedIndex();

      if (sel == -1) {
        JOptionPane.showMessageDialog(this, "No seleccionó la obra social. Seleccione una obra social, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
        return;
      }

      doClose(RET_OK);

      int m = mesjMonthChooser.getMonth() + 1;
      int y = aniojYearChooser.getYear();
      final LocalDate firstDayOfMonth = LocalDate.of(y, m, 1);

      try {
        final ObraSocialDTO o = ObraSocial.SearchByID(osIDs.get(sel));

        LiquidacionObraSocial liquidacionObraSocial = new LiquidacionObraSocial(o.getId(), firstDayOfMonth);
        final ArrayList<LiquidacionJR> l = liquidacionObraSocial.GenerarLiquidacion();
        final JasperPrint jp = LiquidacionObraSocialReport(l);

        //go start
        new Thread(new Runnable() {
          @Override
          public void run() {
            try {
              String shortPDFFileName = String.format("%s-%s.pdf", firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM")), o.getNombre());
              String pdfFile = String.format("%s/%s", Data.SENZU_LIQUIDACIONES, shortPDFFileName);

              Reporter.CopyPDFto(jp, pdfFile);

              String shortCSVFileName = String.format("%s-%s.csv", firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM")), o.getNombre());
              String csvFile = String.format("%s/%s", Data.SENZU_LIQUIDACIONES, shortCSVFileName);

              CSVExporter.GenerarCSV(l, csvFile);

              String[] files = {pdfFile, csvFile};
              String[] shortFiles = {shortPDFFileName, shortCSVFileName};

              if (emailjCheckBox.isSelected()) {
                new Email(
                  o.getContactoEmail(),
                  String.format("Liquidación del mes %s", firstDayOfMonth.format(DateTimeFormatter.ofPattern("MM/yyyy"))),
                  String.format("Estimado %s:\n\nLe enviamos el archivo adjunto con las liquidaciones del mes correspondiente.\n\nSaludos cordiales.\nClínica Senzu.", o.getNombre()),
                  files, shortFiles
                ).Send();

                JOptionPane.showMessageDialog(
                  null,
                  String.format("Se envió correctamente el email a la obra social %s", o.getNombre()),
                  "Éxito: Liquidación enviada",
                  JOptionPane.INFORMATION_MESSAGE
                );
              }
            } catch (JRException e) {
              System.out.printf("?pdf liquidación obra social issue\n");
            } catch (IOException e) {
              System.out.printf("?csv liquidación obra social issue\n");
            } catch (MessagingException e) {
              JOptionPane.showMessageDialog(null, "No se pudo enviar el email. Por favor, verifique:\n\n(1) Su conexión a Internet.\n(2) La configuración del email de la clínica, en `Opciones'.\n\nDe persistir el problema, solicite al administrador verificar el email de contacto de la obra social.", "Error!", JOptionPane.ERROR_MESSAGE);
            }
          }
        }).start();
        //go end

        JasperViewer viewer = new JasperViewer(jp, false);
        viewer.setTitle(
          String.format(
            "Liquidación de Obra Social %s para el mes %s",
            o.getNombre(),
            firstDayOfMonth.format(DateTimeFormatter.ofPattern("MM/yyyy"))
          )
        );
        viewer.setVisible(true);
        viewer.setFitWidthZoomRatio();
      } catch (SQLException e) {
        System.out.printf("?db liquidación obra social issue\n");
      } catch (JRException e) {
        System.out.printf("?print liquidación obra social issue\n");
      }
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
      doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
      doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog
  
  private void doClose(int retStatus) {
    returnStatus = retStatus;
    setVisible(false);
    dispose();
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private kalendar.calendar.JYearChooser aniojYearChooser;
  private javax.swing.JButton cancelButton;
  private javax.swing.JCheckBox emailjCheckBox;
  private javax.swing.JLabel jLabel1;
  private kalendar.calendar.JMonthChooser mesjMonthChooser;
  private javax.swing.JComboBox obraSocialjComboBox;
  private javax.swing.JButton okButton;
  // End of variables declaration//GEN-END:variables

  private int returnStatus = RET_CANCEL;
}
